<?php
namespace App\Admin\Controllers\SalesReport;

use App\Models\Basics\SysPlatAccount;
use App\Models\Basics\AmazonCountry;
use App\Models\Basics\SysArea;
use App\Models\Basics\SysPlat;
use App\Models\SalesReport\MonthlySa;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Support\Facades\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
class MonthlySAController extends AdminController{

    protected $title = '月销售额统计(RMB)';

    protected $filters = [
        'account_id' => null,
        'plat_id' => null,
        'area_id' => null,
        'country_id' => null,
    ];

    protected function grid()
    {
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $this->_initFilters($filters);
        $query = $this->_initQuery($filters);
        $_query = clone $query;
        $headers = MonthlySa::headersField();
        $paginator = $this->_paginator($query);
        $total = $this->_sum($_query,$headers);
        $action = getAction($filtersField);

        $filtersBlade = [];
        $filtersBlade['account_id'] = getOptions(SysPlatAccount::getPlatAccountArray(),$this->filters['account_id']);
        $filtersBlade['plat_id'] = getOptions(SysPlat::$_platformNormal,$this->filters['plat_id']);
        $filtersBlade['area_id'] = getOptions(SysArea::options(),$this->filters['area_id']);
        $filtersBlade['country_id'] = getOptions(AmazonCountry::options(),$this->filters['country_id']);
        $downloadUrl = '/xqc/sales-report/monthly-sa-download?' . http_build_query(array_merge(Request::all(),['_export_' => true]));
        return view('sales-report.monthly-sa.index', compact('paginator','total','headers','filtersBlade','action','downloadUrl'));
    }

    private function _getFilters($filtersField){
        $filters = [];
        foreach ($filtersField as $field){
            $filters[$field] = request($field);
        }
        return $filters;
    }

    private function _initFilters($filters){
        foreach ($filters as $field => $filter){
            $this->filters[$field] = $filter;
        }
    }

    private function _initQuery($filters){
        $query = MonthlySa::query();
        foreach ($filters as $field => $filter){
            if(!$filter)continue;
            if(in_array($field,['account_id','classify_id','plat_id','area_id','country_id'])){
                $query->where($field,$filter);
            }
        }
        return $query;
    }

    private function _paginator($query){
        return $query->paginate((int) (request("per_page",10)))->appends(Request::input());
    }

    private function _sum($query,$headers){
        $sum = $query->selectRaw($this->__getSumFields($headers))->groupBy(1)->first();
        return $sum ? $sum->toArray() : $this->__getSumFieldsInit($headers);
    }

    private function __getSumFields($headers){
        $re = '';
        foreach ($headers as $field => $item){
            if($item['sumField']){
                $re .= 'sum('.$field.') as '.$field.',';
            }else{
                continue;
            }
        }
        return $re.'1';
    }

    private function __getSumFieldsInit($headers){
        $re = [];
        foreach ($headers as $field => $item){
            if($item['sumField']){
                $re[$field] = null;
            }else{
                continue;
            }
        }
        return $re;
    }

    public function download(){
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $query = $this->_initQuery($filters);
        $this->_exeDownload($query);
    }

    private function _exeDownload($query){
        $title1 = ['账号','平台','站点','国家'];
        $title2 = [];
        for($i = MonthlySa::V_NUM - 1; $i >= 0; $i--){
            $title2[] = date("Y.m",strtotime(date('Y-m-01') . "-$i month"));
        }
        $head = array_merge($title1,$title2);
        set_time_limit(0);
        $response = new StreamedResponse(null, 200, [
            'Content-Type'        => 'text/csv;charset=utf-8',
            'Content-Disposition' => 'attachment;filename="(平台)月销售额总表(RMB).csv"',
        ]);
        $response->setCallback(function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->orderBy('id','DESC')->chunk(500, function ($re) use ($fp){
                $data = MonthlySa::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
            fclose($fp);
        });
        $response->send();
        exit(0);
    }

}
